<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\DocumentCategoryStoreRequest;
use App\Models\Document;
use App\Models\DocumentCategory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class DocumentCategoryController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = DocumentCategory::filter(\request()->all())->orderByDesc('id')->paginateFilter(\request('perPage', 10));

        return $this->restful($list);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param DocumentCategoryStoreRequest $request
     * @return JsonResponse|object
     */
    public function store(DocumentCategoryStoreRequest $request)
    {
        $params = $request->validated();
        $params['province'] = json_encode($params['province'], JSON_UNESCAPED_UNICODE);
        DocumentCategory::create($params);

        return $this->restful();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param DocumentCategoryStoreRequest $request
     * @param int $id
     * @return JsonResponse|object
     */
    public function update(DocumentCategoryStoreRequest $request, int $id)
    {
        $params = $request->validated();
        $documentCategory = DocumentCategory::findOrFail($id);
        $params['province'] = json_encode($params['province'], JSON_UNESCAPED_UNICODE);
        $documentCategory->update($params);

        return $this->restful();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     */
    public function destroy(int $id)
    {
        $documentCategory = DocumentCategory::findOrFail($id);
        $documentCategory->delete();
        Document::where('categoryId', $id)->update(['disabled' => 1]);
        return $this->restful();
    }

    public function getOptions() {
        $list = DocumentCategory::select(['id as value', 'name as label'])->get();

        return $this->restful($list);
    }
}
